<template>
	<view class="group-detail">
		<!-- 群信息 -->
		<view class="group-info">
			<image :src="group.avatarUrl" mode="aspectFill" class="group-avatar" />
			<view class="group-name">{{ group.name }}</view>
			<view class="group-desc">{{ group.description || "暂无描述" }}</view>
		</view>

		<!-- 成员列表 -->
		<view class="member-list">
			<view v-if="group && group.members" class="title">
			  群成员（{{ group.members.length }}人）
			</view>
			<scroll-view scroll-x>
				<view class="members">
					<block v-for="(member, index) in memberList" :key="index">
						<view class="member-item">
							<image :src="member.avatar" mode="aspectFill" @click="goToDetail(member.userId)"/>
							<text>{{ member.username }}</text>
							<!-- 踢出成员按钮（仅管理员） -->
							<view v-if="isAdmin && member.role !== 'admin'" class="kick-btn" @click="kickMember(member.userId)">
								<text class="icon">-</text>
							</view>
						</view>
					</block>
				</view>
			</scroll-view>
		</view>

		<!-- 管理员功能区 -->
		<view v-if="isAdmin" class="admin-actions">
			<view class="action-item" @click="deleteGroup">
				<text class="icon">⚠️</text> 解散群聊
			</view>
		</view>
		
		<!-- 成员功能区 -->
		<view v-else class="member-actions">
			<view class="action-item" @click="exitGroup">
				<text class="icon">🚪</text> 退出群聊
			</view>
		</view>

		<!-- 编辑群信息按钮（仅管理员可见） -->
		<view v-if="isAdmin" class="edit-group-btn" @click="editGroupInfo">
			<text class="icon">✏️</text> 修改群信息
		</view>
		
		<!-- 邀请成员 -->
		<view class="invite-btn" @click="inviteMembers">
			+ 邀请好友加入群聊
		</view>
		
		
	</view>
</template>

<script>
import {GroupApi,GroupMembersApi} from "@/api/index.js"
import websocketMixin from '@/utils/mixins/websocketMixin'
	
export default {
	mixins: [websocketMixin],
	data() {
		return {
			groupId: null,
			group: {},
			memberList: [],
			userRole: null
		};
	},
	onLoad(options) {
	    this.groupId = options.groupId; // 从页面加载选项中获取groupId
	    if (!this.groupId) {
	      uni.showToast({
	        title: '群组ID未指定',
	        icon: 'none'
	      });
	    }
	},
	computed: {
		// 判断当前用户是否是管理员
		isAdmin() {
			return this.userRole === "admin";
		}
	},
	onShow(){
		this.getGroupDetails();
	},
	methods: {
		goToDetail(userId) {
			const currentUserId = getApp().globalData.userId;
				
			// 判断是否是自己
			if (userId === currentUserId) {
				uni.navigateTo({
					url: '/pages/mine/user-space'
				});
			}else{
				uni.navigateTo({
					url: `/pages/paper/friend_profile?userId=${userId}`
				});
			}
		},
		// 获取群详情和群成员
		async getGroupDetails() {
			const res = await GroupApi.getGroupInfoById(this.groupId);
			this.group = res.data;
			this.memberList = res.data.members;
			console.log(res);
			
			// 获取当前用户在群中的角色
			const currentUser = this.memberList.find(m => m.userId === getApp().globalData.userId);
			this.userRole = currentUser?.role || "member";
		},
		// 修改群信息
		editGroupInfo() {
			uni.navigateTo({
				url: `/pages/groups/edit_group?groupId=${this.groupId}`
			});
		},
		// 踢出成员
		async kickMember(memberId) {
			uni.showModal({
				title: "提示",
				content: "确定要踢出该成员吗？",
				success: async (res) => {
					if (res.confirm) {
						try {
							await GroupMembersApi.kickMember(this.groupId, memberId);
							uni.showToast({ title: "已踢出", icon: "none" });
							this.memberList = this.memberList.filter(m => m.id !== memberId);
							this.group.members = this.memberList;
							this.getGroupDetails();
						} catch (err) {
							uni.showToast({ title: "操作失败", icon: "none" });
							console.error(err);
						}
					}
				}
			});
		},
		// 解散群聊
		async deleteGroup() {
			uni.showModal({
				title: "警告",
				content: "确定要解散群聊吗？此操作不可恢复！",
				success: async (res) => {
					if (res.confirm) {
						try {
							await GroupApi.deleteGroup(this.groupId);
							uni.showToast({ title: "已解散", icon: "success" });
							setTimeout(() => {
								uni.switchTab({
								    url: '/pages/groups/group'
								});
							}, 1000);
						} catch (err) {
							uni.showToast({ title: "解散失败", icon: "none" });
							console.error(err);
						}
					}
				}
			});
		},
		// 退出群聊
		async exitGroup() {
			uni.showModal({
				title: "提示",
				content: "确定要退出群聊吗？",
				success: async (res) => {
					if (res.confirm) {
						try {
							await GroupMembersApi.exitGroup(this.groupId);
							uni.showToast({ title: "已退出", icon: "success" });
							setTimeout(() => {
								uni.switchTab({
								    url: '/pages/groups/group'
								});
							}, 1000);
						} catch (err) {
							uni.showToast({ title: "退出失败", icon: "none" });
							console.error(err);
						}
					}
				}
			});
		},
		inviteMembers() {
			const groupId = this.groupId;
			uni.navigateTo({
				url: `/pages/groups/select_member?groupId=${groupId}`,
				events: {
					selectMembers: (selected) => {
						this.memberList = [...this.memberList, ...selected];
						this.group.members = this.memberList.length;
					}
				}
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.group-detail {
	padding: 30rpx;

	.group-info {
		text-align: center;
		margin-bottom: 40rpx;

		.group-avatar {
			width: 160rpx;
			height: 160rpx;
			border-radius: 80rpx;
			margin-bottom: 20rpx;
		}

		.group-name {
			font-size: 36rpx;
			font-weight: bold;
			margin-bottom: 10rpx;
		}

		.group-desc {
			color: #999;
			font-size: 28rpx;
		}
	}

	.member-list {
		margin-bottom: 50rpx;

		.title {
			font-size: 32rpx;
			font-weight: bold;
			margin-bottom: 20rpx;
		}

		.members {
			display: flex;
			white-space: nowrap;
		}

		.member-item {
			display: inline-block;
			width: 120rpx;
			margin-right: 20rpx;
			text-align: center;
			position: relative;

			image {
				width: 80rpx;
				height: 80rpx;
				border-radius: 40rpx;
			}

			text {
				display: block;
				font-size: 24rpx;
				color: #666;
			}

			.kick-btn {
				position: absolute;
				top: -10rpx;
				right: -10rpx;
				background-color: #ff4949;
				color: white;
				width: 40rpx;
				height: 40rpx;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 32rpx;
			}
		}
	}

	.admin-actions,
	.member-actions {
		margin-top: 40rpx;

		.action-item {
			display: flex;
			align-items: center;
			color: red;
			font-size: 28rpx;
			margin-bottom: 30rpx;

			.icon {
				margin-right: 10rpx;
			}
		}
	}

	.invite-btn {
		background-color: #07C160;
		color: white;
		text-align: center;
		padding: 25rpx 0;
		border-radius: 40rpx;
		font-size: 32rpx;
	}
}

.edit-group-btn {
	background-color: #1890FF;
	color: white;
	text-align: center;
	padding: 25rpx 0;
	border-radius: 40rpx;
	font-size: 32rpx;
	margin: 40rpx 30rpx;
	display: flex;
	align-items: center;
	justify-content: center;

	.icon {
		margin-right: 10rpx;
	}
}
</style>